/*
 * Create:      柿子
 * CreateDate:  2022/07/13
 * Describe：   视光管理系统 - 验光师工作站 - 验配师工作站
 * */
import React, { Component } from 'react';
import { Card, Steps, Icon, Modal, Tooltip, message } from 'antd';
import { Util } from 'tools';
import { $http } from 'containers/config/https';
import store from 'store';
import asyncComponent from 'routers/AsyncComponent.js';
import PatientBlacklist from 'pages/hospital/component/PatientBlacklist';
import ComprehensiveOptometryRoom from './component/ComprehensiveOptometryRoom';
import PatientsClinicalTabPane from 'pages/workstation/component/PatientsClinicalTabPane';
import ShowCommonNavigationPage from 'pages/workstation/component/ShowCommonNavigationPage';
import './style/index.less';

const icon_name = require('pages/workstation/image/img/icon_name.png');
const icon_gender = require('pages/workstation/image/img/icon_gender.png');
const icon_expense = require('pages/workstation/image/img/icon_expense.png');
const icon_icon = require('pages/workstation/image/img/icon_icon.png');
const icon_name_blocklist = require('pages/workstation/image/img/icon_name_blocklist.png');

const { Step } = Steps;
const confirm = Modal.confirm;
class OptometristWorkstation extends Component {
  constructor(props) {
    super(props);
    var currentPatData = React.$getSessionData('titleData');
    this.state = {
      userData: React.$getSessionData(),
      stepData: [],
      componentSource: {},
      currentPatData, // 当前选中患者信息
      stepCurrent: 0,
    }
  }

  componentDidMount() {
    this.getStepData();
  }

  componentWillUnmount() {
    sessionStorage.removeItem('titleData');
    sessionStorage.removeItem('patientData');
    store.dispatch({
      type: 'CORDefaultValue',
      value: {}
    });
    this.setState = (state, callback) => { return; }
  }

  // 获取动态step组件
  getStepData = async () => {
    try {
      let { userData } = this.state;
      var data = {
        params: [{
          locID: userData?.locID || '',
          hospID: userData?.hospID || '',
          groupID: userData?.groupID || ''
        }]
      }
      let res = await React.$asyncPost(this, '03050093', data);
      var code = '', stepCurrent = 0;
      if (!Util.isEmpty(res.result)) {
        for (var i = 0; i < res.result.length; i++) {
          if (!Util.isEmpty(res.result[i].defaultFlag) && res.result[i].defaultFlag == 'Y') {
            code = res.result[i]
            stepCurrent = i//新增，用于对外组件调用，step默认问题
            break;
          }
        }
      }
      this.setState({
        stepData: res.result,
        componentSource: code,
        stepCurrent
      })
    } catch (error) {
      console.log(error)
    }
  }

  // 切换步骤条
  handleStepsChange = (e) => {
    let { currentPatData } = this.state;
    if (currentPatData && currentPatData.admID) {
      this.setState({ stepCurrent: e })
    } else {
      message.error('请先选择病人！');
    }
  }

  // 点击结束就诊，返回列表
  handleEndOperation = (index, isClear) => {
    var { stepData } = this.state;
    this.setState({
      componentSource: stepData[index],
      stepCurrent: index
    }, () => {
      if (isClear === 'Y') {
        this.setState({
          currentPatData: {}
        })
        sessionStorage.removeItem('titleData');
        sessionStorage.removeItem('patientData');
        setTimeout(() => {
          this.roomChild && this.roomChild.getTableData('N');
        }, 300)
      }
    })
  }

  handleStepItemClick = (item) => {
    var { userData, routeFlag, currentPatData } = this.state;
    if (!(currentPatData && currentPatData.admID)) {
      return;
    }
    if (routeFlag === true) {
      confirm({
        title: '提示',
        content: '当前页面数据未保存，是否需要保存？',
        okText: userData.language == 'EN' ? 'Ok' : '是',
        cancelText: userData.language == 'EN' ? 'cancel' : '否',
        onOk: () => {
          this.setState({
            componentSource: item,
            routeFlag: false, //组件切换后，销毁自组件数据
          })
        },
        onCancel: () => {
          this.setState({
            componentSource: item,
            routeFlag: false
          })
        }
      })
    } else {
      this.setState({
        componentSource: item
      })
    }
  }

  loadStepComponent = () => {
    //获取父组件的参数，渲染组件
    const { componentSource } = this.state;
    if (!Util.isEmpty(componentSource)) {
      const Component = asyncComponent(() => import('./../../' + componentSource.component));
      // console.log('componentSource', componentSource)
      return ('component' in componentSource && componentSource.component && componentSource.component.indexOf('optometry/component/ComprehensiveOptometryRoom.jsx') > -1) ? ( // 综合验光病人列表/验配室病人列表/检查病人列表
        <ComprehensiveOptometryRoom
          paras={{ params: componentSource?.paras || '' }}
          onRef={ref => this.roomChild = ref}
          updatePatData={this.updatePatData}
          handleDoublePatList={this.handleDoublePatList}
        />
      ) : (
        <Component
          paras={{ params: componentSource?.paras || '' }}
          onRef={ref => this.childRef = ref}
          handleEndOperation={this.handleEndOperation}
        />
      )
    }
  }

  // 更新患者信息
  updatePatData = (record) => {
    console.log('record', record)
    this.setState({ currentPatData: record })
  }

  // 双击病人列表更新病人数据并跳转界面
  handleDoublePatList = record => {
    let { stepData, stepCurrent } = this.state;
    let nStepCurrent = stepCurrent < stepData.length ? stepCurrent + 1 : stepCurrent;
    this.setState({ currentPatData: record, stepCurrent: nStepCurrent, componentSource: stepData[nStepCurrent] });
  }

  // 验光师结束检查(取消结束)
  handleEndInspection = () => {
    let { currentPatData, stepCurrent } = this.state;
    if (!(currentPatData && currentPatData.queID)) return;
    let data = {
      params: [{
        queID: currentPatData.queID,
        areaRoomID: currentPatData?.areaRoomID || '',
        statusCode: 'CF'
      }],
    }
    $http.post('urlS', this, {
      code: '17020009',
      data,
      success: function (res) {
        if (res.errorCode === '0') {
          message.success(res.errorMessage || '取消成功');
          stepCurrent > 0 ? this.handleEndOperation(0, 'Y') : '';
          this.roomChild && this.roomChild.handleQuery('N');
        }
      }
    })
  }

  // 添加至黑名单
  addToBlacklist = () => {
    const { currentPatData } = this.state;
    if (!Util.isEmpty(currentPatData)) {
      this.blacklistRef && this.blacklistRef.modifyVisible(true, { ...currentPatData });
    }
  }

  render() {
    let { stepData, stepCurrent, currentPatData, userData } = this.state;
    let patientUrl = !Util.isEmpty(currentPatData) ? currentPatData.patImage : '';
    let windowHost = window.location && window.location.protocol && window.location.host ? (window.location.protocol + '//' + window.location.host) : (window.location && window.location.origin ? window.location.origin : '');
    let patientImg = patientUrl ? (patientUrl.indexOf('http') !== -1 ? patientUrl : windowHost + patientUrl) : '';

    let componentOption = []
    stepData && stepData.map((item, index) => {
      componentOption.push(
        <Step key={index} style={{ cursor: 'pointer' }}
          title={(
            <Tooltip title={userData.language == 'EN' ? item.ENDesc : item.title}>
              {userData.language == 'EN' ? item.ENDesc : item.title}
            </Tooltip>
          )}
          disabled={false}
          onClick={() => this.handleStepItemClick(item)} />)
    })

    return (
      <div className="optometrist-workstation out-patient-style">
        <div style={{ float: 'left', width: '10.7%' }}>
          <Card>
            <div>
              <div style={{ textAlign: 'center' }}>
                {
                  !Util.isEmpty(patientUrl) ? <img className='splice-patient-img' src={patientImg} /> : <div className={currentPatData && currentPatData.patSexCode == '1' ?
                    'splice-boys' : (currentPatData && currentPatData.patSexCode == '2' ? 'splice-girls' : 'splice-girls')}></div>
                }
              </div>
              <div style={{ fontSize: '14px' }}>
                <div style={{ padding: '0 0 0 30px' }}>
                  {/* <Tooltip placement="topLeft" title={!Util.isEmpty(currentPatData) ? (currentPatData?.blackListobj?.blackFlag === 'Y' ? '修改黑名单信息' : '添加至黑名单') : '请先选择患者'}> */}
                  <div
                    style={{ color: '#333333', fontWeight: 'bold' }}
                  // style={{ color: '#333333', fontWeight: 'bold', cursor: 'pointer' }}
                  // onClick={this.addToBlacklist}
                  >
                    <img src={currentPatData?.blackListobj?.blackFlag === 'Y' ? icon_name_blocklist : icon_name} style={{ marginRight: 20, marginBottom: 3 }} />
                    <span>{currentPatData ? currentPatData.patName || '--' : '--'}</span>
                  </div>
                  {/* </Tooltip> */}

                  <div style={{ marginTop: 10 }}>
                    <img src={icon_gender} style={{ marginRight: 20, marginBottom: 3 }} />
                    {currentPatData ? currentPatData.patSexDesc || '--' : '--'}
                  </div>

                  <div style={{ marginTop: 10 }}>
                    <img src={icon_expense} style={{ marginRight: 20, marginBottom: 3 }} />
                    {currentPatData ? currentPatData.patAge || '--' : '--'}
                  </div>

                  <div style={{ marginTop: 10 }}>
                    <img src={icon_icon} style={{ marginRight: 20, marginBottom: 3 }} />
                    {currentPatData ? currentPatData.patMobile || '--' : '--'}
                  </div>

                  <div style={{ marginTop: 10 }}>
                    <Icon className='statusdesc-splice' style={{ marginRight: 20 }} />
                    {currentPatData ? currentPatData.patSocialStatusDesc || '--' : '--'}
                  </div>

                  <div style={{ marginTop: 10 }} >
                    <Icon className='typeDesc-splice' style={{ marginRight: 20 }} />
                    {currentPatData ? currentPatData.patTypeDesc || '--' : '--'}
                  </div>

                  <div style={{ color: '#007AFF', marginTop: 10, marginBottom: 10 }}>
                    <Icon className='account-splice' style={{ marginRight: 20 }} />
                    {currentPatData ? currentPatData.accountBalance || '--' : 0}
                  </div>
                </div>
              </div>
            </div>
          </Card>

          <Card style={{ marginTop: 5, height: store.getState().tableHeight.y - 165 }}>
            <ShowCommonNavigationPage patientData={currentPatData}></ShowCommonNavigationPage>
          </Card>
        </div>

        <div className="ow-card-right">
          <div className="ow-steps flex">
            <div className="doctor-step-cls" style={{ marginTop: 10, marginLeft: '5%', marginRight: '5%', width: '94%' }}>
              <Steps
                size="small"
                type="navigation"
                current={stepCurrent}
                onChange={this.handleStepsChange}
              >
                {componentOption}
              </Steps>
            </div>
            <div
              style={{ width: '5.3%', borderLeft: '1px solid #eee', textAlign: 'center', padding: '0 6px', boxSizing: 'border-box' }}
              className="flex-center"
            >
              <div style={{ cursor: currentPatData && currentPatData.queID ? 'pointer' : 'no-drop', color: currentPatData && currentPatData.queID ? 'red' : '#999' }} onClick={this.handleEndInspection}>取消结束</div>
            </div>
          </div>
          <div className="ow-content">
            <PatientsClinicalTabPane
              height="100%"
              patientData={currentPatData}
              current={stepCurrent}
              loadStepCompent={this.loadStepComponent()}
            >
            </PatientsClinicalTabPane>
          </div>
        </div>

        {/* 添加至黑名单 */}
        <PatientBlacklist handleQuery={null} onRef={ref => this.blacklistRef = ref} />
      </div>
    );
  }
};

export default OptometristWorkstation;